// components/index-custom-nav/index.js
let sys_js = require("../../utils/system.js");

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    keys: {
      type: Object,
      value: []
    }
  },

  observers: {
    'keys': function (keys) {
      //如果需要开启定时器
      if (keys && keys.length > 0) {
        //开启计时器
        this.countDownTimer();
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    timerObj: {
      timerId: null,
      isEnd: false,
      endTime: '',
      item: null
    },
    index: 0,
    statusBarHeight: 0,
    navBarHeight: 0
  },

  lifetimes: {
    ready() {
      let sysInfo = sys_js.navInfo();
      this.setData({
        statusBarHeight: sysInfo.statusBarHeight,
        navBarHeight: sysInfo.navBarHeight
      });
    },
    // 页面销毁
    detached() {
      this.clearTimer();
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 计时器**********
    countDownTimer() { //倒计时函数
      let tmpTimerObj = this.data.timerObj;
      // 先清除计时器
      this.clearTimer();
      //1s调用一次
      let that = this;
      let timerId = setTimeout(function () {
        that.data.index++;
        if (that.data.index == that.data.keys.length) {
          that.data.index = 0;
        }
        that.countDownTimer();
      }, 5000);
      tmpTimerObj.timerId = timerId;
      // 渲染，然后每隔一秒执行一次倒计时函数
      this.setData({
        timerObj: tmpTimerObj,
        index: that.data.index
      })
    },
    // 清除计时器
    clearTimer() {
      if (this.data.timerObj.timerId) {
        clearTimeout(this.data.timerObj.timerId);
        this.data.timerObj.timerId = null;
      }
    },
    onSearch() {
      this.triggerEvent("search", null, null);
    }
  }
})